const express = require('express')
const app = express()
const path = require('path')
const fs = require('fs')
const WebSocketServer = require('ws').Server
const http = require('http'); //require 引用内置模块http

app.use(express.static(path.join(__dirname, 'public')))
//监听端口
app.listen(8088,()=>{
    console.log('HTTP Server is running on: http://localhost:%s', 8080)
})
// app.get('*',(req,res)=>{
//     let urlPath = req.path
//     if(urlPath == '/'||urlPath=='/index.html'||urlPath=='/index'||urlPath=='') {
//         console.log('返回index.html')
//         res.end(fs.readFileSync(`./index.html`))
//     }
// })
// 保存用户id
let users = [1]
let mess = [2]
let wss = new WebSocketServer({ port: 8181 });
wss.on('connection', function (ws) {
    console.log('client connected');
    ws.on('message', function (message) {
        message = JSON.parse(message)
        // 判断状态
        if(message.state==1) {
            // 注册用户时间
            console.log('66666')
            users.push({
                id:message.id,
                name:message.name,
                time:message.time,
                state:1
            })
            // 将更新的用户信息发送给所有用户
            updateAllUsername()
        }
        if(message.state==4) {
            // 注册用户时间
            console.log('4444')
            let id = message.id
            users= users.filter((item)=>{
                return item.id!==id
            })
            // 给所有还在用的用户更新列表
            updateAllUsername()
        }
        if(message.state==2) {
            // 注册用户时间
            console.log('4444')
            mess.push({
                id:message.id,
                idshow:message.idshow,
                name:message.name,
                mes:message.mes,
                time:message.time,
            })
            // 给所有还在用的用户更新列表
            updateAllmess()
        }
    });
});

function updateAllUsername () {
    for(let item of wss.clients){
        console.log(users)
        item.send(JSON.stringify(users))
    }
}
function updateAllmess () {
    for(let item of wss.clients){
        console.log(mess)
        item.send(JSON.stringify(mess))
    }
}




http.createServer(function (req, res) {
    var pathname = req.url //把请求网址交给url 对象处理
    // var bodyStr = webPath[pathname]; //如果访问路径没有被 webPath 指定会返回
    res.setHeader("Access-Control-Allow-Origin", "*");

    if(pathname=='/inituser'){
        console.log('6666')
        res.writeHead(200, {'Content-Type': 'text/plain'}); //设置文件头信息
        res.end(JSON.stringify(users));
        console.log('6666')
    }
    if(pathname=='/initmess'){
        res.writeHead(200, {'Content-Type': 'text/plain'}); //设置文件头信息
        res.end(JSON.stringify(mess));
    }

}).listen(9527, '127.0.0.1'); //绑定IP 和端口
console.log('Server running at http://127.0.0.1:9527/'); //控制台输出提示
